package at.ac.tuwien.dse.health.dashboard;

import at.ac.tuwien.dse.health.entity.Account;
import at.ac.tuwien.dse.health.security.SecurityContext;
import at.ac.tuwien.dse.health.security.authentication.AuthenticationManager;
import at.ac.tuwien.dse.health.security.web.SecurityFilter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
@Controller
public class LoginController {
	private static final Logger LOGGER = LogManager.getLogger(LoginController.class);
	@Inject
	AuthenticationManager authenticationManager;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginView() {
		if (SecurityContext.getRole() != null) {
			return new ModelAndView("redirect:/dashboard/");
		}
		return new ModelAndView("login");
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@Transactional
	public ModelAndView performLogin(@RequestParam("username") String username,
									 @RequestParam("password") String password,
									 HttpServletRequest request) {

		if (!isBlank(username) && !isBlank(password)) {
			Account account = authenticationManager.authenticate(username, password);
			if (account != null) {
				SecurityFilter.setAuthenticated(request.getSession(true), account.getUser());
			} else {
				SecurityFilter.setAuthenticated(request.getSession(false), null);
			}
		}
		return loginView();
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout() {
		if (SecurityContext.getRole() == null)
			return loginView();
		((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession(true).invalidate();
		SecurityContext.setRole(null);
		ModelAndView modelAndView = loginView();
		modelAndView.getModelMap().put("afterLogout", true);
		return modelAndView;
	}
}
